{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy.io as sio \n",
    "import numpy as np\n",
    "from plot_conf_mat import plot_confusion_matrix\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import data from matlab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fichier = sio.loadmat('fichier.mat') # Download the features/labels generated by the matlab script\n",
    "Sequences_arduino = sio.loadmat('input/sequences_arduino.mat') #Download the sequences correposnding\n",
    "\n",
    "label = fichier['Labels']\n",
    "data_fourier = fichier['Data_fourier']\n",
    "sequences_arduino = Sequences_arduino['sequences'].reshape(90,)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Separate the True and False labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "var_D = np.where(label == 1) # Find the 1 corresponding\n",
    "index_true = var_D[0]\n",
    "len_index = index_true.shape\n",
    "num_index_true = int (len_index[0])\n",
    "\n",
    "data_no_p300 = np.delete(data_fourier, index_true, axis = 0) # ALl the features corresponding to 0\n",
    "\n",
    "data_p300 = np.zeros([num_index_true, 320])# All the features corresponding to 1\n",
    "for i in range(num_index_true):\n",
    "    data_p300[i] = data_fourier[index_true[i],:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create the data set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = np.append(data_p300, data_no_p300[0:num_index_true,:],axis=0) # Create set of the same size\n",
    "y = np.append(np.ones([num_index_true, 1]), np.zeros([num_index_true, 1]),axis=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reduce the dimension of the problem using PCA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.decomposition import RandomizedPCA\n",
    "n_components_PCA = 80\n",
    "pca = RandomizedPCA(n_components=n_components_PCA, random_state= 7).fit(X)\n",
    "X_pca = pca.transform(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training / Test set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.cross_validation import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.4, random_state=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SVM Classifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "from sklearn.grid_search import GridSearchCV\n",
    "\n",
    "#Find the best parameter\n",
    "param_grid = {'C': [ 0.1, 1e3, 5e3, 1e4, 5e4, 1e5],\n",
    "              'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1]}  \n",
    "\n",
    "clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)\n",
    "y_train = y_train.reshape(int(y_train.shape[0]),)\n",
    "clf = clf.fit(X_train, y_train)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Accuracy and Confusion Matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "y_pred = clf.predict(X_test)\n",
    "binary_acc = round(accuracy_score(y_test,y_pred),3)\n",
    "conf_mat = confusion_matrix(y_test,y_pred, [0, 1] )\n",
    "plot_confusion_matrix(conf_mat, classes = [0,1],normalize=False, title='Confusion matrix',cmap=plt.cm.Blues)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Predict the word of the user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from guess_combination import predict_word\n",
    "\n",
    "predicted_combination = predict_word(0, 19, data_fourier, sequences_arduino, pca, clf)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Assess the accuracy to predict the good word"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "patient_combination = [1, 1, 4, 2, 4, 5, 7, 2, 9, 4, 5, 8, 9, 8, 3, 8, 8, 5, 4]\n",
    "\n",
    "acc = round(accuracy_score(predicted_combination,Ben_combination),3)\n",
    "\n",
    "conf_mat_bis= confusion_matrix(Ben_combination,predicted_combination, [1, 2, 3, 4, 5, 6, 7, 8, 9] )\n",
    "\n",
    "classes = [1, 2, 3, 4, 5, 6, 7, 8, 9] "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Assess the bitrate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bitrate import bitrate\n",
    "bitrate_minute = bitrate(acc,9)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
